<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="public/bower_components/angular/angular.js"></script>
</head>
<body ng-app="mainApp" ng-controller="CartController">

<div>
    <h1>Item List</h1>
    <div ng-repeat="item in items">
        <img src="">
        <span ng-bind="item.name"></span>
        <span ng-bind="item.price"></span>
        <button ng-click="addToCart($index)">buy</button>
    </div>
</div>
<hr>
<div>
    <ul>
        <li ng-repeat="c in cart">
            <span>{{c.item.name}}</span>
            <span>{{c.item.price}}</span>
            <span><input type="number" min="0" ng-model="c.count"></span>
        </li>
    </ul>
</div>
<h2>{{total}}</h2>
<script>

    angular.module('mainApp',[])
            .controller('CartController',function ($scope) {
                var t = -1
                var total = 0
                var items = [
                    {name:'iPhone',price:35},
                    {name:'iMac',price:100},
                    {name:'iPad',price:85},
                ]
                $scope.items = items
                $scope.total = total
                var cart = []
                //var cartItem = {item:item,count:2}
                $scope.cart = cart
                $scope.addToCart = function (index) {
                    var exist = cart.some(function (o,inx,array) {
                        t = inx
                        return angular.equals(o.item,items[index])
                    });
                    if(!exist){
                        var cartItem = {item:items[index],count:1}
                        cart.push(cartItem)
                    }else{
                        cart[t].count ++;
                    }
                }
                $scope.$watch('cart',function (n,o) {
                    $scope.total = 0
                    console.log('11')
                    cart.forEach(function (c,i) {
                        $scope.total += c.item.price * c.count;
                        if(c.count == 0)
                            cart.splice(i,1)
                    })


                },true)

            })

</script>
</body>
</html>